import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { RadioGroup, Radio, TextArea, Button,Upload, Image,Toast } from '@douyinfe/semi-ui';
import { IconPlus, IconMinus } from '@douyinfe/semi-icons';
import { Select, Slider } from '@arco-design/web-react';
import { useDispatch, useSelector } from 'react-redux';
import { setUploadedImage, setCurrentImage, addLayerImage, selectLayerImages, clearImages } from '@/store';
import { useImageUpload } from '@/hooks/useImageUpload';
import { textToImage, clickSelect,boxSelect,smearSelect,partitionSelect } from '@/api/imageEdit';
import add from "@/assets/images/imageEdit/add.svg";
import person_Subject from "@/assets/images/imageEdit/person_Subject.svg";
import general_Subject from "@/assets/images/imageEdit/general_Subject.svg";

import styles from "./index.module.scss";
import { 
  TAB_LIST, 
  UPLOAD_CONFIG, 
  MENU_HEIGHTS,
} from './constants';
import { RATIO_OPTIONS } from '../Results/constants';
import { useBlobUrlManager } from './hooks/useBlobUrlManager';
import UploadComponent from './components/UploadComponent';
import ToolButtons from './components/ToolButtons';
import ReferencePromptSection from './components/ReferencePromptSection';
import ReferenceImageSection from './components/ReferenceImageSection';
import HistoryModal from './components/HistoryModal';

export default function MainEdit({ 
  onTabChange,
  currentMenuKey,
  currentMenuTitle,
  typeValue, 
  onTypeChange, 
  proportion, 
  setProportion, 
  qualityValue, 
  setQualityValue, 
  quantityValue, 
  setQuantityValue,
  selectedTool,
  onToolChange,
  toolSize,
  onToolSizeChange,
  selectedRatio,
  setSelectedRatio,
  hasDataToSubmit,
  selectedPoints,
  selectGreenPoints,
  selectionRects,
  brushStrokes,
  currentImageUrl,
  canvasDrawingRef,
  erasureText,
  setErasureText,
  showMainEdit
}) {
  const dispatch = useDispatch();
  const layerImages = useSelector(selectLayerImages);
  const [currentTabKey, setCurrentTabKey] = useState('ZT');
  const [historyModal, setHistoryModal] = useState(false);
  const [imgObj, setImgObj] = useState({});
  const [imgtypeValue, setImgTypeValue] = useState(1);
  const [promptText, setPromptText] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [selectedPreset, setSelectedPreset] = useState('person'); // 预设项选择状态
  
  // 使用自定义Hook管理blob URLs
  const { createBlobUrl, cleanupUnusedUrls } = useBlobUrlManager();

  // 预设项点击处理函数
  const handlePresetClick = (presetType) => {
    setSelectedPreset(presetType);
  };

  // 处理画幅比例切换
  const handleRatioChange = (ratio) => {
    setSelectedRatio(ratio);
  };



  // 提交任务处理函数
  const handleSubmitTask = async () => {
    try {
      if (selectedTool === 'press' && selectedPoints.length > 0) {
        // 原有点选工具提交逻辑（暂时注释）
         const requestData = {
           isErase: imgtypeValue == '1' ? 1 : 0,
           sourceImgUrl: currentImageUrl,
           foregroundPointCoordinates: selectedPoints.map(point => ({
             x: point.x,
             y: point.y
           })),
           backgroundPointCoordinates: selectGreenPoints.map(point => ({
              x: point.x,
              y: point.y
           }))
         };
        const response = await clickSelect(requestData);
        console.log('点选任务提交成功:', response);
      }
      if (selectedTool === 'graphic' && selectionRects.length > 0) {
        // 点选工具提交（包括内容擦除）
        const requestData = {
          isErase: imgtypeValue == '1' ? 1 : 0,
          sourceImgUrl: currentImageUrl,
          coordinates: selectionRects.map(point => ({
            tlx: point.tlx,
            tly: point.tly,
            brx: point.brx,
            bry: point.bry
          }))
        };
       const response = await boxSelect(requestData);
       console.log('框选任务提交成功:', response);
     }
     if(selectedTool === 'brush'&&brushStrokes.length > 0) {
       // 获取当前离屏canvas图片（原尺寸）
       const canvasImageData = canvasDrawingRef.current?.getCanvasImage();
       if (!canvasImageData) {
         console.error('无法获取canvas图片数据');
         return;
       }
       
       // 将base64转换为File对象
       const base64ToFile = (base64Data, fileName) => {
         const arr = base64Data.split(',');
         const mime = arr[0].match(/:(.*?);/)[1];
         const bstr = atob(arr[1]);
         let n = bstr.length;
         const u8arr = new Uint8Array(n);
         while (n--) {
           u8arr[n] = bstr.charCodeAt(n);
         }
         return new File([u8arr], fileName, { type: mime });
       };
       
       const maskFile = base64ToFile(canvasImageData, `mask_${Date.now()}.png`);
       // 上传mask图片
       const uploadResult = await uploadFile({
         fileInstance: maskFile,
         name: maskFile.name
       });
       
       if (!uploadResult.success) {
         console.error('mask图片上传失败:', uploadResult.error);
         return;
       }
       
       // 涂选工具提交（包括内容擦除）
       const requestData = {
         isErase: imgtypeValue == '1'? 1 : 0,
         sourceImgUrl: currentImageUrl,
         maskImageUrl: uploadResult.url
       };
      const response = await smearSelect(requestData);
       console.log('涂选任务提交成功:', response);
     }
     if (selectedTool === 'segmentation' && erasureText.trim() !== '') {
       // 分割工具提交
       const requestData = {
         isErase: 0, // 分割工具默认不擦除
         erasureText: erasureText.trim(),
         sourceImgUrl: currentImageUrl
       };
       const response = await partitionSelect(requestData);
       console.log('分割任务提交成功:', response);
     }
    } catch (error) {
      console.error('提交任务失败:', error);
    }
  };
  
  // 使用图片上传Hook
  const { handleUpload: uploadFile, validateFile, uploading, progress } = useImageUpload({
    onSuccess: (result) => {
      // 上传成功后更新为服务器URL
      handleUpload({
        url: result.url,
        type: currentMenuKey === 'layer' ? 'layer' : 'single',
        uploadKey: currentMenuKey === 'layer' ? 'layer' : 'uploadImg'
      });
    },
    onError: (error) => {
      console.error('上传失败:', error);
    }
  });
  

  
  // 计算属性
  const tabList = useMemo(() => 
    TAB_LIST.map(item => ({
      ...item,
      active: item.key === currentTabKey
    })), [currentTabKey]
  );
  
  const currentTabTitle = useMemo(() => 
    TAB_LIST.find(item => item.key === currentTabKey)?.title || '主体识别',
    [currentTabKey]
  );
  
  const heights = MENU_HEIGHTS[currentMenuKey] || MENU_HEIGHTS.default;
  
  // 事件处理函数
  const handleTabChange = useCallback((menu) => {
    setCurrentTabKey(menu.key);
    onTabChange?.(menu);
  }, [onTabChange]);
  
  const handleHistoryClick = useCallback((e) => {
    e.stopPropagation(); // 阻止事件冒泡，防止触发Upload的点击事件
    setHistoryModal(true);
  }, []);
  
  const handleHistoryModalCancel = useCallback(() => {
    setHistoryModal(false);
  }, []);
  
  const handleHistoryModalConfirm = useCallback(() => {
    setHistoryModal(false);
  }, []);
  
  const handleUpload = useCallback(({ url, file, type, uploadKey}) => {
    let imageUrl;
    
    // 如果传入的是file对象（包含fileInstance），创建本地预览URL
    if (file && file.fileInstance) {
      imageUrl = createBlobUrl(file.fileInstance);
    } 
    // 如果传入的是上传成功后的URL，直接使用
    else if (url) {
      imageUrl = url;
    } 
    else {
      console.error('缺少必要的文件或URL参数');
      return;
    }
    
    // 更新Redux store
    const storeKey = `${currentMenuKey}_${uploadKey}`;
    dispatch(setUploadedImage({ key: storeKey, imageUrl }));
    
    // layer模式下添加到layerImages数组
    if (currentMenuKey === 'layer') {
      dispatch(addLayerImage(imageUrl));
    }
    
    // 如果是单张图片上传，设置为当前图片（layer模式除外）
    if ((type === 'single' || uploadKey === 'main' || uploadKey === 'single' || uploadKey === 'uploadImg') && currentMenuKey !== 'layer') {
      dispatch(setCurrentImage(imageUrl));
    }
      
    setImgObj(prevImgObj => {
      if (type === 'array') {
        const currentArray = prevImgObj[currentMenuKey] || [];
        return {
          ...prevImgObj,
          [currentMenuKey]: [...currentArray, imageUrl]
        };
      } else {
        const targetKey = `${currentMenuKey}_${uploadKey}`;
        return {
          ...prevImgObj,
          [targetKey]: imageUrl
        };
      }
    });
  }, [currentMenuKey, createBlobUrl, dispatch]);
  
  const handleImgTypeChange = useCallback((e) => {
    const newValue = e.target.value || 1;
    setImgTypeValue(newValue);
  }, []);
  
  const handleToolClick = useCallback((toolKey) => {
    onToolChange?.(toolKey);
  }, [onToolChange]);

  // 文生图处理函数
  const handleTextToImage = useCallback(async () => {
    // 只有在文生图相关的菜单键时才调用API
    if (!['text', 'pic', 'multi'].includes(currentMenuKey)) {
      return;
    }

    if (!promptText.trim()) {
      console.warn('请输入提示词');
      return;
    }

    setIsGenerating(true);
    try {
      const requestData = {
        text: promptText,
        imgRatio: proportion,
        resolution: qualityValue,
        imgCount: quantityValue
      };

      const response = await textToImage(requestData);
      
      if (response && response.data) {
        const imageUrl = response.data.imageUrl || response.data.url;
        if (imageUrl) {
          dispatch(setCurrentImage(imageUrl));
          dispatch(setUploadedImage({ key: `${currentMenuKey}_generated`, imageUrl }));
        }
      }
    } catch (error) {
      console.error('文生图生成失败:', error);
    } finally {
      setIsGenerating(false);
    }
  }, [promptText, proportion, qualityValue, quantityValue, currentMenuKey, dispatch]);
  
  // 监听imgObj和layerImages变化，清理不再使用的blob URLs
  useEffect(() => {
    const currentUrls = [];
    
    // 收集imgObj中的blob URLs
    Object.values(imgObj).forEach(urls => {
      if (Array.isArray(urls)) {
        urls.forEach(url => {
          if (typeof url === 'string' && url.startsWith('blob:')) {
            currentUrls.push(url);
          }
        });
      } else if (typeof urls === 'string' && urls.startsWith('blob:')) {
        currentUrls.push(urls);
      }
    });
    
    // 收集layerImages中的blob URLs
    layerImages.forEach(url => {
      if (typeof url === 'string' && url.startsWith('blob:')) {
        currentUrls.push(url);
      }
    });
    
    cleanupUnusedUrls(currentUrls);
  }, [imgObj, layerImages, cleanupUnusedUrls]);
  
  // 防止页面刷新时的提示
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);

  // 组件卸载时清理图片数据
  useEffect(() => {
    return () => {
      dispatch(clearImages());
    };
  }, [dispatch]);
  
  // 渲染不同菜单类型的内容
  const renderMenuContent = useCallback(() => {
    if (!['pic', 'multi'].includes(currentMenuKey)) return null;
    
    return (
      <>
        <div className={styles.titleSection}>参考特征</div>
        <div 
          className={`${styles.area} ${currentMenuKey === 'pic' ? styles.areaWithPadding : ''}`}
          style={{ maxHeight: heights.area }}
        > 
          {currentMenuKey === 'pic' && (
            <>
              <div className={styles.tabs}>
                {tabList.map(item => (
                  <div 
                    key={item.key} 
                    className={item.active ? styles.isActive : styles.noActive} 
                    onClick={() => handleTabChange(item)}
                  >
                    {item.title}
                  </div>
                ))}
              </div>
              <UploadComponent 
                title={currentTabTitle} 
                uploadKey={currentTabKey}
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={handleHistoryClick}
                imgObj={imgObj}
              />
            </>
          )}
          {currentMenuKey === 'multi' && (
            <>
              <UploadComponent 
                title="主体图" 
                uploadKey='ZT' 
                subtitle="" 
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={handleHistoryClick}
                imgObj={imgObj}
              />
              <UploadComponent 
                title="场景图" 
                uploadKey='CJ' 
                subtitle="" 
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={handleHistoryClick}
                imgObj={imgObj}
              />
              <UploadComponent 
                title="风格图" 
                uploadKey='FG' 
                subtitle="" 
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={handleHistoryClick}
                imgObj={imgObj}
              />
            </>
          )}
        </div>
      </>
    );
  }, [currentMenuKey, heights.area, tabList, handleTabChange, currentTabTitle, handleUpload, handleHistoryClick, imgObj]);
  
  // 渲染图片上传区域
  const renderImageUploadSection = useCallback(() => (
    <>
      <div className={styles.titleSection}>上传图片</div>
      <div 
        className={styles.area}
        style={{ 
          maxHeight: heights.area,
          paddingRight: '8px' 
        }}
      >
        <div className={styles.layerItem}>
          <Upload 
            {...UPLOAD_CONFIG} 
            className={`${styles.uploadSection} ${styles.uploadFullSize}` }  
            customRequest={async ({ file, onSuccess, onError }) => {
              try {
                const isValid = await validateFile(file);
                if (!isValid) {
                  onError?.(new Error('文件验证失败'));
                  return;
                }
                
                // 执行上传
                const result = await uploadFile(file, file.name);
                
                if (result.success) {
                  onSuccess?.(result);
                } else {
                  onError?.(result.error || new Error('上传失败'));
                }
              } catch (error) {
                console.error('上传失败:', error);
                onError?.(error);
              }
            }}
            disabled={uploading}
            onAcceptInvalid={() => {
              Toast.error({ content: '文件类型不支持，请重新选择文件', stack: true });
            }}
          >
          <div className={styles.uploadPlaceholder}>
            {uploading ? (
              <div className={styles.uploadingState}>
                <div className={styles.uploadText}>上传中... {progress}%</div>
                <div className={styles.progressBar} style={{ width: `${progress}%` }}></div>
              </div>
            ) : (
              <>
                <Image
                  src={add}
                  preview={false}
                  className={styles.uploadIcon}
                  draggable={false}
                />
                <div className={styles.uploadText}>
                  从<span onClick={handleHistoryClick}>「历史文件」</span>上传
                </div>
              </>
            )}
          </div>
          </Upload>
        </div>
      </div>
    </>
  ), [heights.area, handleHistoryClick, handleUpload, imgObj, currentMenuKey,uploading]);
  

  
  return showMainEdit ? (
    <div className={styles.mainEdit}>
      <div className={styles.top}>
        <div className={styles.header}>
          <div className={styles.title}>{currentMenuTitle}</div>
          {currentMenuKey === 'text' && (
            <RadioGroup 
              type='button' 
              buttonSize='small' 
              className={styles.typeGroup}
              value={typeValue}
              onChange={onTypeChange}
            >
              <Radio value={1}>
                <div className={styles.typeItem}>图片生成</div>
              </Radio>
              <Radio value={2}>
                <div className={styles.typeItem}>元素生成</div>
              </Radio>
            </RadioGroup>
          )}
          {currentMenuKey === 'image' && (
            <RadioGroup 
              type='button' 
              buttonSize='small' 
              className={styles.typeGroup}
              value={imgtypeValue}
              onChange={handleImgTypeChange}
            >
              <Radio value={1}>
                <div className={styles.typeItem}>内容擦除</div>
              </Radio>
              <Radio value={2}>
                <div className={styles.typeItem}>内容替换</div>
              </Radio>
            </RadioGroup>
          )}
        </div>
        {['pic', 'multi'].includes(currentMenuKey) && renderMenuContent()}
        {['image', 'layer'].includes(currentMenuKey) && renderImageUploadSection()}
        {['text', 'pic', 'multi'].includes(currentMenuKey) && (
          <ReferencePromptSection 
            heights={heights}
            promptText={promptText}
            setPromptText={setPromptText}
            isGenerating={isGenerating}
          />
        )}
        {['image', 'layer'].includes(currentMenuKey) && (
          <div className={styles.imageContainer}>
            <ToolButtons 
              selectedTool={selectedTool} 
              onToolClick={handleToolClick} 
            />
            {selectedTool=='brush'&&(
              <div className={styles.brushSizeContainer}>
                <div className={styles.brushSizeWrapper}>
                  <div>画笔尺寸</div>
                  <div className={styles.brushSizeSliderContainer}>
                    <div className={styles.brushSizeIcon}>
                      <div className={styles.brushSizeIconSmall}></div>
                    </div>
                    <Slider
                      className={styles.slider}
                      min={10}
                      max={200}
                      value={toolSize}
                      onChange={onToolSizeChange}
                    />
                    <div className={styles.brushSizeIcon}>
                      <div className={styles.brushSizeIconLarge}></div>
                    </div>
                  </div>
                  <div className={styles.brushSizeInput}>
                    <IconMinus 
                      onClick={() => onToolSizeChange(Math.max(10, toolSize - 1))}
                      style={{ cursor: 'pointer' }}
                    />
                    <div>{toolSize}px</div>
                    <IconPlus 
                      onClick={() => onToolSizeChange(Math.min(200, toolSize + 1))}
                      style={{ cursor: 'pointer' }}
                    />
                  </div>
                </div>
              </div>
            )}
            {selectedTool=='segmentation'&&(
              <TextArea 
                style={{padding:'8px'}}
                placeholder='请输入您想要更改的内容...'
                value={erasureText}
                onChange={(value) => setErasureText(value)}
              />
            )}
            {selectedTool=='preset'&&(
              <div className={styles.presetContainer}>
                <div 
                  className={`${styles.presetItem} ${selectedPreset === 'person' ? styles.selected : ''}`}
                  onClick={() => handlePresetClick('person')}
                >
                  <Image
                    src={person_Subject}
                    className={styles.img}
                    preview={false}
                    draggable={false}
                  />
                  <div className={styles.presetLabel}>人</div>
                </div>
                <div 
                  className={`${styles.presetItem} ${selectedPreset === 'general' ? styles.selected : ''}`}
                  onClick={() => handlePresetClick('general')}
                >
                  <Image
                    src={general_Subject}
                    className={styles.img}
                    preview={false}
                    draggable={false}
                  />
                  <div className={styles.presetLabel}>通用</div>
                </div>
              </div>
            )}
          </div>
        )}
        {['layer'].includes(currentMenuKey)&&(
          <div className={styles.ratioSelector}>
            <div className={styles.ratioLabel}>画幅比</div>
            <div className={styles.ratioOptions}>
              {RATIO_OPTIONS.map(ratio => (
                <div 
                  key={ratio}
                  className={`${styles.ratioOption} ${selectedRatio === ratio ? styles.selected : ''}`}
                  onClick={() => handleRatioChange(ratio)}
                >
                  {ratio}
                </div>
              ))}
            </div>
          </div>
        )}
        {['image', 'layer'].includes(currentMenuKey) && (
          <div className={styles.submitButtonContainer}>
            <Button 
              className={`button buttonPrimary ${styles.submitButton}`}
              disabled={!hasDataToSubmit}
              onClick={handleSubmitTask}
            >
              提交任务
            </Button>
          </div>
        )}
        {currentMenuKey === 'image' && imgtypeValue === 2 && (
          <ReferenceImageSection 
            currentMenuKey={currentMenuKey}
            onUpload={handleUpload}
            onHistoryClick={handleHistoryClick}
            imgObj={imgObj}
          />
        )}
        {currentMenuKey === 'image' && imgtypeValue === 2 && (
          <>
            <div className={`${styles.titleSection} ${styles.titleSectionMargin}`}>参考提示词</div>
            <div className={`${styles.area} ${styles.referenceTextArea}`}>
              <TextArea 
                placeholder='可再次输入对于图像合成的提示词...'
                value={promptText}
                onChange={(value) => setPromptText(value)}
              />
              <Button 
              className='button buttonPrimary'
              onClick={handleTextToImage}
              loading={isGenerating}
              disabled={isGenerating}
            >
            {isGenerating ? '生成中...' : '立即生成'}
          </Button>
            </div>
          </>
        )}
      </div>
      {['text', 'pic', 'multi'].includes(currentMenuKey) && (
        <div className={styles.bottom}>
          <div className={styles.selectSection}>
            <Select 
              className={styles.select} 
              value={proportion} 
              onChange={setProportion}
            >
              <Select.Option value={'16:9'}>16:9</Select.Option>
              <Select.Option value={'9:16'}>9:16</Select.Option>
              <Select.Option value={'4:3'}>4:3</Select.Option>
              <Select.Option value={'1:1'}>1:1</Select.Option>
            </Select>
            <Select 
              className={styles.select} 
              value={qualityValue} 
              onChange={setQualityValue}
            >
              <Select.Option value={'1K'}>1K</Select.Option>
              <Select.Option value={'2K'}>2K</Select.Option>
            </Select>
            <Select 
              className={styles.select} 
              value={quantityValue} 
              onChange={setQuantityValue}
            >
              <Select.Option value={1}>1张</Select.Option>
              <Select.Option value={4}>4张</Select.Option>
            </Select>
          </div>
          <Button 
            className='button buttonPrimary'
            onClick={handleTextToImage}
            loading={isGenerating}
            disabled={isGenerating}
          >
            {isGenerating ? '生成中...' : '立即生成'}
          </Button>
        </div>
      )}
      <HistoryModal 
        visible={historyModal}
        onCancel={handleHistoryModalCancel}
        onConfirm={handleHistoryModalConfirm}
      />
    </div>
  ) : null;
}